<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;

// 用户控制器
class User extends Backend{
    // 构造函数
    public function __construct()
    {
        parent::__construct();

        // 全局
        $this->UserModel=model('User.User');
        $this->RegionModel=model('Region');
        $this->RecordModel=model('User.Record');
    }

    // 用户列表
    public function index(){
        // 接收关键词
        $keywords=$this->request->param('keywords','');
        $start=$this->request->param('start','');
        $end=$this->request->param('end','');

        // 封装一个查询条件的数值
        $where=[];

        if(!empty($keywords)){
            $where['nickname|email']=['like',"%$keywords%"];
        }

        // 判断开始时间是否为空
        if(!empty($start)){
            // 标准时间转化为时间戳
            $starttime=strtotime($start);
            $where['createtime']=['EGT',$starttime];
        }

        // 判断结束时间是否为空
        if(!empty($end)){
            // 标准时间转化为时间戳
            $endtime=strtotime($end);
            $where['createtime']=['ELT',$endtime];
        }

        // 当开始时间和结束时间都不为空时
        if(!empty($start) && !empty($end))
        {
            $starttime=strtotime($start);
            $endtime=strtotime($end);
            $where['createtime']=['between',[$starttime,$endtime]];
        }

        // 总数
        $count=$this->UserModel->where($where)->count();

        $userlist=$this->UserModel
                        ->with(['provinces','citys','districts'])
                        ->order('createtime','desc')
                        ->where($where)->paginate(10);

        // echo $this->UserModel->getLastSql();
        // exit;

        // 分页调用
        $pagestr=$userlist->render();

        // 赋值
        $this->assign([
            'count'=>$count,
            'userlist'=>$userlist,
            'pagestr'=>$pagestr,
            'keywords'=>$keywords,
            'start'=>$start,
            'end'=>$end,
        ]);

        return $this->fetch();
    }

    // 用户编辑
    public function edit(){
        $userid=$this->request->param('userid',0);
        $userlist=$this->UserModel->where(['id'=>$userid])->find();

        // 查询地区表的省份数据
        $province=$this->RegionModel->where(['grade'=>1])->select();

        // 判断当前这个用户是否有选择省份
        if(empty($this->LoginUser['province'])){
            $city=[];
        }else{
            $city=$this->RegionModel->where(['parentid'=>$this->LoginUser['province']])->select();
        }

        // 判断当前用户是否选择城市
        if(empty($this->LoginUser['city'])){
            $district=[];
        }else{
            $district=$this->RegionModel->where(['parentid'=>$this->LoginUser['city']])->select();
        }

        if($this->request->isPost()){
            // 获取全部数据
            $params=$this->request->param();

            // 判断邮箱是否正确
            if($params['email'] != $userlist['email']){
                $data['auth']=0;
            }

            $oldpass=$this->request->param('oldpass','');
            $password=$this->request->param('password','');
            $repass=$this->request->param('repass','');


            $data=[
                'id'=>$userlist['id'],
                'email'=>$params['email'],
                'nickname'=>$params['nickname'],
                'sex'=>$params['sex'],
                'province'=>$params['province'],
                'city'=>$params['city'],
                'district'=>$params['district'],
                'content'=>$params['content'],
            ];

            if(!empty($oldpass)){
                // 获取数据库里的密码盐
                $oldsalt=$userlist['salt'];
                $oldpass=md5($oldpass.$oldsalt);

                // 判断输入的旧密码和数据库里的密码是否一致
                if($oldpass != $userlist['password']){
                    $this->error('您输入的旧密码不正确，请重新输入');
                    exit;
                }

                // 判断是否等于原来的密码
                $nowpass=md5(trim($password).$oldsalt);
                if($nowpass == $userlist['password']){
                    $this->error('新密码不能和旧密码相同');
                    exit;
                }

                if($password != $repass){
                    $this->error('您输入的新密码和确认密码不一致，请重新输入');
                    exit;
                }

                $salt=randstr(10);
                $password=md5(trim($password).$salt);

                $data['salt']=$salt;
                $data['password']=$password;
            }

            
            // 头像修改
            if($_FILES['avatar']['size'] > 0)
            {
                $avatar=upload('avatar');
                if($avatar===FALSE){
                    $this->error('头像修改失败');
                    exit;
                }else{
                    $data['avatar'] = 'uploads/'.$avatar;
                }
            }

            // 修改背景
            if($_FILES['cover']['size'] > 0){
                $cover=upload('cover');
                if($cover===FALSE){
                    $this->error('封面修改失败');
                    exit;
                }else{
                    $data['cover']='uploads/'.$cover;
                }
            }
            
            $result=$this->UserModel->validate('common/User/User.profile')->isUpdate(true)->save($data);

            if($result === FALSE){
                // 上传的图片要删除
                @is_file($data['avatar']) && @unlink($data['avatar']);
                @is_file($data['cover']) && @unlink($data['cover']);

                $this->error($this->UserModel->getError());
                exit;
            }else{
                // 修改成功后，将原来的图片删除
                $avatar=ltrim($userlist['avatar'],"/");
                @is_file($avatar) && @unlink($avatar);

                $cover=ltrim($userlist['cover'],"/");
                @is_file($cover) && @unlink($cover);
            }

            $this->success('修改完成',url('admin/user.user/index'));
            exit;
        }

        $this->assign([
            'userlist'=>$userlist,
            'province'=>$province,
            'city'=>$city,
            'district'=>$district,
        ]);

        return $this->fetch();
    }

    // 查询地区的
    public function area(){
        if($this->request->isPost()){
            // 获取的地区码
            $code=$this->request->param('code',0);

            // 根据地区码查询城市、区域
            $arealist=$this->RegionModel->where(['parentid'=>$code])->select();

            // 返回json数据
            return json($arealist);
        }
    }

    public function record(){

        $userid=$this->request->param('userid','');
        $userlist=$this->RecordModel->where(['userid'=>$userid])->paginate(10);

        $pagestr=$userlist->render();

        $this->assign([
            'userlist'=>$userlist,
            'pagestr'=>$pagestr,
        ]);

        return $this->fetch();
    }

    public function allrecord(){
        $userlist=$this->RecordModel->with(['user'])->paginate(10);
        $count=$this->RecordModel->count();
        $pagestr=$userlist->render();

        $this->assign([
            'userlist'=>$userlist,
            'pagestr'=>$pagestr,
            'count'=>$count,
        ]);

        return $this->fetch();
    }

    // 删除用户
    public function del()
    {
        $success = [
            'result' => false,
            'msg' => ''
        ];

        if($this->request->isAjax())
        {
            $ids = $this->request->param('ids',0);
            
            $result = $this->UserModel->destroy($ids);

            if($result === FALSE){
                $success['result'] = false;
                $success['msg'] = $this->UserModel->getError();
            }else
            {
                $success['result'] = true;
                $success['msg'] = '删除成功';
            }
            return json($success);
        }
    }
}